import React, { useState, useEffect, useCallback } from 'react';
import { connect } from 'dva';
import EditTemplate from '@/components/EditTemplate';
import CapitalSource from '@/pages/components/capitalSource';
import { Table, Card, Row, Button, Modal, Input, message, Select } from 'antd';
import { timeFormat } from '@/utils/common';
import { getStatus } from '@/utils/business';
import Status from '@/pages/components/Status';
import AuthButton from '@/components/AuthButton';
import SelectInput from '@/components/SelectInput';
import moment from 'moment';

const { TextArea } = Input;
const BuildEdit = ({ location, dispatch, dict, url, approve }: any) => {
  const [isDetail, setIsDetail] = useState(false);
  const {
    id,
    transType,
    fromType = 3,
    readOnly,
    isApprove = false,
  } = location.query;
  const pointType = { 3: 'PLAN', 1: 'ANNUAL', 9: 'MONEY' }[fromType];
  const [approveList, setapproveList] = useState([]);
  const [showModal, setshowModal] = useState(false);
  const [comment, setcomment] = useState('');
  const [buildType, setbuildType] = useState('');
  const currentYear = new Date().getFullYear();
  const yearList: any = [];
  approve.year &&
    yearList.push({
      label: `${currentYear}年`,
      value: currentYear,
    });
  approve.nextYear &&
    yearList.push({
      label: `${currentYear + 1}年`,
      value: currentYear + 1,
    });
  const [detail, setDetail] = useState(null);
  const projectSelect = (name, uuid) => {
    console.log(`name:${name}, value :${uuid}`);
    setDetail({ ...detail, projectUuid: uuid });
  };
  const setTotal = data => {
    console.log(data.total);
    setDetail({
      ...detail,
      uuid: reportUuid,
      fundSource: data,
      totalInvestment: data.total,
    });
    // totalInvestment
  };
  const build = [
    {
      title: '基础信息',
      list: [
        {
          key: 'name',
          type: 'custom',
          label: '项目名称',
          span: 12,
          placeholder: '请输入项目名称',
          render:
            fromType == 1 && !id ? (
              <SelectInput onChange={projectSelect}></SelectInput>
            ) : readOnly ? null : (
              <Input></Input>
            ),
        },
        {
          key: ['project', 'no'],
          type: 'text',
          label: '项目ID',
          span: 12,
        },
        {
          key: 'ownerOrgUnit',
          type: 'text',
          label: '业主单位',
          span: 12,
        },
        {
          key: 'professionDataUuid',
          type: 'select',
          label: '行业领域',
          asyncopt: {
            url: '/api/data/v1/getDataList',
            data: {
              code: 'profession',
            },
          },
          span: 12,
          placeholder: '请选择',
          rules: [{ required: true }],
        },
        {
          key: 'buildType', //TODO: 这里未补充
          type: 'select',
          label: '项目性质',
          value: 'BUILD',
          span: 12,
          options: [
            {
              label: '建设',
              value: 'BUILD',
            },
            {
              label: '保障',
              value: 'PURCHASE_SERVICE',
            },
          ],
          prop: {
            onChange: type => changeProjectType(type),
          },
          placeholder: '请选择',
          rules: [{ required: true }],
        },
        {
          key: 'serviceTypeDataUuid',
          type: 'select',
          label: '项目类型',
          span: 12,
          asyncopt: {
            url: '/api/data/v1/getDataList',
            data: {
              code: 'service',
            },
          },
          placeholder: '请选择',
          rules: [{ required: true }],
        },
        {
          key: 'buildYear',
          type: 'select',
          label: '申报年份',
          span: 12,
          options: yearList,
          placeholder: '请选择',
          rules: [{ required: true }],
        },
      ],
    },
    {
      title: '项目简介',
      list: [
        {
          key: 'description',
          type: 'textarea',
          label: '项目简介',
          span: 24,
          prop: { rows: 4 },
          rules: [{ required: true }],
        },
        {
          key: 'examine',
          type: 'textarea',
          label: '考核',
          span: 24,
          prop: { rows: 4 },
          rules: [{ required: true }],
        },
        {
          key: 'buildNesscessary',
          type: 'textarea',
          label: '建设必要性',
          span: 24,
          prop: { rows: 4 },
          rules: [{ required: true }],
        },
        {
          key: 'buildTarget',
          type: 'textarea',
          label: '建设目标',
          span: 24,
          prop: { rows: 4 },
          rules: [{ required: true }],
        },
        {
          key: 'survey',
          type: 'textarea',
          label: '调研情况',
          span: 24,
          prop: { rows: 4 },
          rules: [{ required: true }],
        },
      ],
    },
    {
      title: '前期准备',
      list: [
        {
          key: 'formation',
          type: 'input',
          label: '规划编制',
          span: 12,
          placeholder: '请输入',
        },
        {
          key: 'authentication',
          type: 'input',
          label: '专家认证',
          span: 12,
          placeholder: '请输入',
        },
      ],
    },
    {
      title: '建设周期',
      list: [
        {
          key: 'startDateTime',
          type: 'datepicker',
          label: '启动时间',
          span: 12,
          prop: { picker: 'month' },
          placeholder: '请输入',
          rules: [{ required: true }],
        },
        {
          key: 'endDateTime',
          type: 'datepicker',
          label: '预计完成时间',
          prop: { picker: 'month' },
          span: 12,
          placeholder: '请输入',
          rules: [{ required: true }],
        },
      ],
    },
    {
      title: '资金申请',
      list: [
        {
          key: 'totalInvestment',
          type: 'input',
          label: '建设总投资',
          disabled: true,
          span: 12,
          prop: {
            addonAfter: '万元',
          },
          placeholder: '请输入',
          rules: [
            {
              required: true,
              pattern: new RegExp(/^-?\d+/, 'g'),
              message: '只能输入数字',
            },
          ],
        },
        {
          key: 'fundSource',
          type: 'custom',
          label: ' 资金来源',
          span: 24,
          rules: [{ required: true }],
          render: <CapitalSource readOnly={readOnly} onChange={setTotal} />,
        },
      ],
    },
    {
      title: '其他信息',
      list: [
        {
          key: 'contactPersonName',
          type: 'input',
          label: '联系人',
          span: 12,
          placeholder: '请输入',
          rules: [{ required: true }],
        },
        {
          key: 'contactPersonPhone',
          type: 'input',
          label: '联系人电话',
          span: 12,
          placeholder: '请输入',
          rules: [{ required: true }],
        },
        {
          key: 'liablePersonName',
          type: 'input',
          label: '负责人',
          span: 12,
          rules: [{ required: true }],
        },
        {
          key: 'liablePersonPhone',
          type: 'input',
          label: '负责人电话',
          span: 12,
          rules: [{ required: true }],
        },
        {
          key: 'remark',
          type: 'textarea',
          label: '备注',
          prop: { rows: 4 },
          span: 24,
        },
        {
          key: 'createTime',
          type: 'text',
          label: '申报日期',
          span: 24,
          hidden: !readOnly,
        },
        {
          key: 'fileList',
          type: 'upload',
          label: '其他附件',
          span: 24,
        },
      ],
    },
  ];
  const purchase = [
    {
      title: '基础信息',
      list: [
        {
          key: 'name',
          type: 'custom',
          label: '项目名称',
          span: 12,
          placeholder: '请输入项目名称',
          render:
            fromType == 1 && !id ? (
              <SelectInput onChange={projectSelect}></SelectInput>
            ) : readOnly ? null : (
              <Input></Input>
            ),
        },
        {
          key: ['project', 'no'],
          type: 'text',
          label: '项目ID',
          span: 12,
        },
        {
          key: 'ownerOrgUnit',
          type: 'text',
          label: '业主单位',
          span: 12,
        },
        {
          key: 'professionDataUuid',
          type: 'select',
          label: '行业领域',
          asyncopt: {
            url: '/api/data/v1/getDataList',
            data: {
              code: 'profession',
            },
          },
          span: 12,
          placeholder: '请选择',
          rules: [{ required: true }],
        },
        {
          key: 'buildType', //TODO: 这里未补充
          type: 'select',
          label: '项目性质',
          span: 12,
          value: 'PURCHASE_SERVICE',
          options: [
            {
              label: '建设',
              value: 'BUILD',
            },
            {
              label: '保障',
              value: 'PURCHASE_SERVICE',
            },
          ],
          prop: {
            onChange: type => changeProjectType(type),
          },
          placeholder: '请选择',
          rules: [{ required: true }],
        },
        {
          key: 'serviceTypeDataUuid',
          type: 'select',
          label: '项目类型',
          span: 12,
          asyncopt: {
            url: '/api/data/v1/getDataList',
            data: {
              code: 'service',
            },
          },
          placeholder: '请选择',
          rules: [{ required: true }],
        },
        {
          key: 'buildYear',
          type: 'select',
          label: '申报年份',
          span: 12,
          options: yearList,
          placeholder: '请选择',
          rules: [{ required: true }],
        },
      ],
    },
    {
      title: '项目简介',
      list: [
        {
          key: 'description',
          type: 'textarea',
          label: '项目简介',
          span: 24,
          prop: { rows: 4 },
          placeholder: '请输入',
          rules: [{ required: true }],
        },
        {
          key: 'paperLimit',
          type: 'inputnumber',
          label: '合同期限',
          span: 12,
          prop: { rows: 4 },
          placeholder: '请输入',
          rules: [{ required: true }],
        },
        {
          key: 'paperAmount',
          type: 'input',
          label: '合同金额',
          span: 12,
          placeholder: '请输入',
          prop: {
            addonAfter: '万元/年',
            rows: 4,
          },
          rules: [
            {
              required: true,
              pattern: new RegExp(/^-?\d+/, 'g'),
              message: '只能输入数字',
            },
          ],
        },
      ],
    },
    {
      title: '资金申请',
      list: [
        {
          key: 'totalInvestment',
          type: 'inputnumber',
          label: '总投资',
          disabled: true,
          span: 12,
          prop: {
            addonAfter: '万元',
          },
          placeholder: '请输入',
          rules: [
            {
              required: true,
              pattern: new RegExp(/^-?\d+/, 'g'),
              message: '只能输入数字',
            },
          ],
        },
        {
          key: 'fundSource',
          type: 'custom',
          label: ' 资金来源',
          span: 24,
          rules: [{ required: true }],
          render: <CapitalSource readOnly={readOnly} onChange={setTotal} />,
        },
      ],
    },

    {
      title: '其他信息',
      list: [
        {
          key: 'contactPersonName',
          type: 'input',
          label: '联系人',
          span: 12,
          placeholder: '请输入',
          rules: [{ required: true }],
        },
        {
          key: 'contactPersonPhone',
          type: 'input',
          label: '联系人电话',
          span: 12,
          placeholder: '请输入',
          rules: [{ required: true }],
        },

        {
          key: 'remark',
          type: 'textarea',
          label: '备注',
          prop: { rows: 4 },
          span: 24,
          placeholder: '请输入',
        },
        {
          key: 'createTime',
          type: 'text',
          label: '申报日期',
          span: 24,
          placeholder: '请输入',
          hidden: !readOnly,
        },
        {
          key: 'fileList',
          type: 'upload',
          label: '其他附件',
          span: 24,
          placeholder: '请输入',
        },
      ],
    },
  ];

  const [project, setProject] = useState(build);
  const transUrl = {
    3: '/api/project/report/v1/planToAnnual',
    5: '/api/project/report/v1/storeToAnnual',
  };
  // 如果类型为1则为普通年度项目转过来
  const updateUrl =
    fromType == 1
      ? '/api/project/report/v1/annualReport/create'
      : '/api/project/report/v1/annualReport/update';
  const saveUrl = transType ? transUrl[fromType] : updateUrl;
  const columns = [
    { title: '审批节点', dataIndex: 'name', width: 150 },
    {
      title: '审批时间',
      dataIndex: 'createTime',
      width: 250,
      render: (text, data) => (getStatus(data, 3) ? text : ''),
    },
    {
      title: '审批结果',
      dataIndex: 'result',
      width: 150,
      render: (text, data) => <Status data={data} type={3} />,
    },
    { title: '审批意见', dataIndex: 'comment' },
  ];
  const getApproveList = id => {
    //---------------- 获取审批节点 ---------
    readOnly &&
      dispatch({
        type: '$request/post',
        payload: {
          url: '/api/project/approve/v1/result/list',
          data: { uuid: id, pointType },
        },
      }).then(res => {
        const list = res.map(item => {
          return {
            ...item,
            createTime: timeFormat(item.createTime),
            name: item.department.name + '审批',
          };
        });
        setapproveList(list);
      });
  };
  let reportUuid = null;
  useEffect(() => {
    if (id) {
      setIsDetail(readOnly);
      const urlObj: any = {
        1: '/api/project/report/v1/annualReport/detail',
        3: '/api/project/report/v1/planReport/detail',
        5: '/api/project/report/v1/storeReport/detail',
      };
      dispatch({
        type: '$request/post',
        payload: {
          url:
            url ||
            (fromType
              ? urlObj[fromType]
              : '/api/project/report/v1/annualReport/detail'),
          data: {
            uuid: id,
            page: 0,
            size: 10,
          },
        },
      }).then(res => {
        console.log('储备项目申报详情：', res);
        if (res) {
          getApproveList(res.uuid);
          setDetail({
            ...res,
            professionDataUuid: res.professionData.uuid,
            serviceTypeDataUuid: res.serviceTypeData.uuid,
            projectUuid: res.project.uuid,
            createTime: timeFormat(res.createTime),
            startDateTime: readOnly
              ? timeFormat(res.startDate, 'YYYY-MM')
              : moment(res.startDate),
            endDateTime: readOnly
              ? timeFormat(res.endDate, 'YYYY-MM')
              : moment(res.endDate),
          });
          reportUuid = res.uuid;
        } else {
          setDetail({});
        }
        changeProjectType(res.buildType);
      });
    }
  }, []);

  const changeProjectType = type => {
    setbuildType(type);
    if (type == 'BUILD') {
      setProject([...build]);
    } else {
      setProject([...purchase]);
    }
  };
  const preproccess = data => {
    const fileUuidList = data.fileList
      ? data.fileList.map(item => item.uuid)
      : [];
    return {
      fileUuidList,
      ...data,
    };
  };
  const handleResult = type => {
    if (!comment && !type) {
      message.error('拒绝时请输入审批意见');
      return;
    }
    if (!detail || !detail.approveResult) {
      return message.error('项目信息不正确');
    }
    dispatch({
      type: '$request/post',
      payload: {
        url: '/api/project/approve/v1/approve',
        data: {
          projectType: 'ANNUAL',
          comment: comment,
          result: type,
          uuid: detail.approveResult.uuid,
        },
      },
    }).then(() => {
      message.success('审批成功');
      dispatch({ type: '$router/back' });
    });
  };
  return (
    <div>
      <EditTemplate
        filters={project}
        initialValues={{
          ...detail,
          buildType: buildType || (detail && detail.buildType),
        }}
        updateUrl={saveUrl}
        readOnly={isDetail}
        preproccess={preproccess}
        footer={
          isApprove && (
            <Button type="primary" onClick={() => setshowModal(true)}>
              审批
            </Button>
          )
        }
      />
      {readOnly && (
        <Card title="审批信息">
          <Table
            bordered
            tableLayout="fixed"
            dataSource={approveList}
            columns={columns}
          ></Table>
        </Card>
      )}
      <Modal
        title="审批意见"
        visible={showModal}
        okText="通过"
        cancelText="拒绝"
        onCancel={() => setshowModal(false)}
        footer={[
          <AuthButton
            key="back"
            onClick={() => handleResult(false)}
            role="examine_annual_project"
          >
            拒绝
          </AuthButton>,
          <AuthButton
            type="primary"
            onClick={() => handleResult(true)}
            role="examine_annual_project"
          >
            通过
          </AuthButton>,
        ]}
      >
        <TextArea
          placeholder="审批意见，拒绝时必填"
          value={comment}
          onChange={e => setcomment(e.target.value)}
        />
      </Modal>
    </div>
  );
};

export default connect((state: any) => state.base)(BuildEdit);
